import pygame
from pygame import Rect, font


class Button:
    def __init__(self, text, pos, color, font_size=20):
        self.text = text
        self.pos = pos
        self.color = color
        self.font = pygame.font.SysFont('Arial', font_size)
        self.clicked = False

    def draw(self, surface):
        text_surface = self.font.render(self.text, True, self.color)
        surface.blit(text_surface, self.pos)

    def is_clicked(self, mouse_pos):
        text_rect = self.font.render(self.text, True, self.color).get_rect(topleft=self.pos)
        if text_rect.collidepoint(mouse_pos):
            self.clicked = True
            return True
        return False


class Text:
    def __init__(self, text, pos, color, font_size=20):
        self.text = text
        self.pos = pos
        self.color = color
        self.font = pygame.font.SysFont('Arial', font_size)

    def set_text(self, text):
        self.text = text

    def draw(self, surface):
        text_surface = self.font.render(self.text, True, self.color)
        surface.blit(text_surface, self.pos)


class Slider:
    def __init__(self, pos, length, min_val, max_val, initial_val):
        self.pos = pos
        self.length = length
        self.min_val = min_val
        self.max_val = max_val
        self.val = initial_val
        self.radius = 10
        self.track_color = (128, 128, 128)
        self.thumb_color = (200, 200, 200)
        self.thumb_pos = pos[0] + (initial_val - min_val) / (max_val - min_val) * length

    def draw(self, surface):
        pygame.draw.line(surface, self.track_color, (self.pos[0], self.pos[1]), (self.pos[0] + self.length, self.pos[1]), 5)
        pygame.draw.circle(surface, self.thumb_color, (int(self.thumb_pos), self.pos[1]), self.radius)

    def update(self, mouse_pos):
        if abs(mouse_pos[1] - self.pos[1]) < self.radius and self.pos[0] <= mouse_pos[0] <= self.pos[0] + self.length:
            self.thumb_pos = mouse_pos[0]
            self.val = (self.thumb_pos - self.pos[0]) / self.length * (self.max_val - self.min_val) + self.min_val


class Panel:
    def __init__(self, rect):
        self.rect = rect
        self.components = []
        self.scroll_y = 0
        self.grid_energy = None
        self.cell_size = 20
        self.running = False
        self.playing = False

    def set_grid_energy(self, energy_map):
        self.grid_energy = energy_map

    def add_component(self, component):
        self.components.append(component)

    def draw(self, surface):
        # 绘制面板背景
        pygame.draw.rect(surface, (40, 40, 40), self.rect)
        
        # 绘制网格边框
        if self.grid_energy:
            for y in range(len(self.grid_energy)):
                for x in range(len(self.grid_energy[0])):
                    # 将能量值映射到亮度(0-255)
                    brightness = int(min(255, max(0, self.grid_energy[y][x] * 255)))
                    # 根据自养/异养参数设置颜色
                    if hasattr(self, 'gene_stats') and '自养-异养' in self.gene_stats['细胞特性']:
                        ah_value = self.gene_stats['细胞特性']['自养-异养']
                        if ah_value > 0:  # 自养生物偏绿
                            color = (0, brightness, 0)
                        else:  # 异养生物偏红
                            color = (brightness, 0, 0)
                    else:
                        color = (brightness, brightness, 0)
                    
                    # 计算黄色边框亮度(0-255)
                    border_brightness = int(min(255, max(0, self.grid_energy[y][x] * 2.55)))
                    border_color = (border_brightness, border_brightness, 0)  # 纯黄色
                    
                    # 绘制单元格边框
                    cell_rect = pygame.Rect(
                        self.rect.left + x * self.cell_size,
                        self.rect.top + y * self.cell_size,
                        self.cell_size,
                        self.cell_size
                    )
                    pygame.draw.rect(surface, color, cell_rect, 1)
                    pygame.draw.rect(surface, border_color, cell_rect, 2)  # 加粗黄色边框

        # 创建裁剪区域防止内容溢出
        clip_rect = pygame.Rect(self.rect.left, self.rect.top, self.rect.width, self.rect.height)
        surface.set_clip(clip_rect)

        # 先绘制按钮组件（放在顶部）
        button_components = [comp for comp in self.components if isinstance(comp, Button)]
        other_components = [comp for comp in self.components if not isinstance(comp, Button)]

        for button in button_components:
            button.draw(surface)

        # 再绘制其他组件（考虑滚动位置）
        for comp in other_components:
            comp.draw(surface)

        # 重置裁剪区域
        surface.set_clip(None)

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.play_button.is_clicked(event.pos):
                self.playing = not self.playing
                self.play_button.text = "Pause" if self.playing else "Play"
            elif self.reset_button.is_clicked(event.pos):
                self.running = False
                self.playing = False
                self.play_button.text = "Play"
            elif isinstance(event, Slider):
                event.update(event.pos)


class GeneStatDisplay:
    def __init__(self, rect, font):
        # 扩大显示区域高度
        self.rect = pygame.Rect(rect.left, rect.top, rect.width, rect.height * 3)
        self.padding = 10
        self.line_height = 20  # 进一步减小行间距
        self.group_spacing = 20  # 分组间距
        
        # 统一字体配置
        self.font_size = 14
        self.desc_font_size = 12
        try:
            # 使用统一字体
            self.font = pygame.font.Font('C:/Windows/Fonts/simsun.ttc', self.font_size)
            self.desc_font = pygame.font.Font('C:/Windows/Fonts/simsun.ttc', self.desc_font_size)
        except Exception as e:
            print(f"字体加载失败: {e}")
            # 回退到系统字体
            self.font = pygame.font.SysFont('Arial', self.font_size)
            self.desc_font = pygame.font.SysFont('Arial', self.desc_font_size)
        self.stats = {}
        self.scroll_y = 0

    def update_stats(self, genetics, sim_stats):
        if genetics is not None and sim_stats is not None:
            genes = genetics.decode_gene()
            
            # 合并相似数据项
            self.stats = {
                '基本信息': {
                    '存活时间': sim_stats.get('age', 0),
                    '细胞数量': sim_stats.get('count', 0),
                    # '基因编码': tuple(genetics.genetic_code)
                },
                '细胞特性': {
                    '自养-异养': genes['autotrophic_heterotrophic']['value'],
                    '防御-进攻': genes['defense_offense']['value'],
                    '静止-运动': genes['static_motion']['value'],
                    '代谢低-高': genes['low_metabolism_high_metabolism']['value'],
                    '寿命长-短': genes['long_life_short_life']['value'],
                    '排斥-吸引': genes['attract_repel']['value'],
                    '能量': sim_stats.get('current_energy', 0)
                    # '分裂阈值': genes['division_threshold']['value']
                }
            }
            # 添加描述信息
            self.descriptions = {
                '自养-异养': genes['autotrophic_heterotrophic']['description'],
                '防御-进攻': genes['defense_offense']['description'],
                '静止-运动': genes['static_motion']['description'],
                '代谢低-高': genes['low_metabolism_high_metabolism']['description'],
                '寿命长-短': genes['long_life_short_life']['description'],
                '排斥-吸引': genes['attract_repel']['description'],
                '能量': sim_stats.get('current_energy', 0)
                # '分裂阈值': genes['division_threshold']['description']
            }

    def draw(self, surface):
        y = self.rect.top + self.padding - self.scroll_y
        
        # 绘制细胞生活类型概括
        if hasattr(self, 'stats') and '细胞特性' in self.stats:
            traits = []
            for trait, value in self.stats['细胞特性'].items():
                if trait == '自养-异养' and value > 0:
                    traits.append('自养')
                elif trait == '自养-异养' and value <= 0:
                    traits.append('异养')
                elif trait == '防御-进攻' and value < 0:
                    traits.append('防御')
                elif trait == '防御-进攻' and value > 0:
                    traits.append('进攻')
                elif trait == '静止-运动' and value == 0:
                    traits.append('静止')
                elif trait == '静止-运动' and value > 0:
                    traits.append('运动')
                elif trait == '代谢低-高' and value > 20:
                    traits.append('代谢低')
                elif trait == '代谢低-高' and value >= 20:
                    traits.append('代谢高')
                elif trait == '寿命长-短' and value > 20:
                    traits.append('寿命长')
                elif trait == '寿命长-短' and value <= 20:
                    traits.append('寿命短')
                elif trait == '排斥-吸引' and value > 0:
                    traits.append('吸引同类')
                elif trait == '排斥-吸引' and value <= 0:
                    traits.append('排斥同类')
            
            # 将traits数组分成两部分，分别渲染两行文本
            half_length = len(traits) // 2
            first_line_traits = traits[:half_length]
            second_line_traits = traits[half_length:]

            summary_first_line = '，'.join(first_line_traits)
            summary_second_line = '，'.join(second_line_traits)

            summary_text_first_line = self.font.render(f"细胞类型: {summary_first_line}", True, (200, 200, 255))
            summary_text_second_line = self.font.render(summary_second_line, True, (200, 200, 255))

            surface.blit(summary_text_first_line, (self.rect.left + self.padding, y))
            y += self.line_height
            surface.blit(summary_text_second_line, (self.rect.left + self.padding, y))
            y += self.line_height * 2
        
        for group, items in self.stats.items():
            # 绘制分组标题
            group_title = self.font.render(group, True, (255, 255, 200))
            surface.blit(group_title, (self.rect.left + self.padding, y))
            y += self.line_height

            for label, value in items.items():
                # 只绘制在可见区域内的文本
                if y + self.line_height > self.rect.top and y < self.rect.bottom:
                    # 绘制主参数
                    value_str = str(value)

                    # 自动换行处理
                    max_width = self.rect.width - 2 * self.padding
                    text_lines = []
                    current_line = f'{label}: {value_str.split('(')[0].strip()}'

                    # 分割文本为多行
                    split_pos = len(current_line)  # 默认设置为字符串长度
                    if self.font.size(current_line)[0] > max_width:
                        # 找到最后一个可以放下的空格位置
                        for i in range(len(current_line), 0, -1):
                            if current_line[i - 1] == ' ' and self.font.size(current_line[:i])[0] <= max_width:
                                split_pos = i
                                break
                        if split_pos == len(current_line):  # 没有空格可以分割，强制分割
                            split_pos = len(current_line) - 1

                    text_lines.append(current_line[:split_pos])
                    current_line = current_line[split_pos:].lstrip()

                    text_lines.append(current_line)

                    # 绘制所有行
                    for line in text_lines:
                        text = self.font.render(line, True, (200, 200, 200))
                        surface.blit(text, (self.rect.left + self.padding, y))
                        y += self.line_height

                    # 绘制解释文本（如果有）
                    if '(' in value_str and ')' in value_str:
                        desc = value_str[value_str.find('(') + 1:value_str.find(')')]
                        desc_text = self.desc_font.render(desc, True, (120, 120, 120))
                        surface.blit(desc_text, (self.rect.left + self.padding + 10, y))
                        y += self.line_height

                    # 减少行间距以显示更多参数
                    y += self.line_height // 3
                else:
                    y += self.line_height

            # 添加分组间距
            y += self.group_spacing


class GeneEditor:
    def __init__(self, rect, font):
        self.rect = rect
        self.font = font
        self.genes = {}

    def update_genes(self, genetics):
        if genetics:
            self.genes = genetics

    def draw(self, surface):
        title = self.font.render('基因编辑器', True, (255, 255, 200))
        surface.blit(title, (self.rect.left + 10, self.rect.top + 10))

        y = self.rect.top + 40
        for gene, data in self.genes.items():
            text = self.font.render(f'{gene}: {data["value"]} ({data["description"]})', True, (180, 180, 250))
            surface.blit(text, (self.rect.left + 20, y))
            y += 25